package com.mcp.client.transport;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Stdio传输实现
 * 通过标准输入输出与MCP服务通信
 */
public class StdioTransport implements McpTransport {
    private final Process process;
    private final BufferedReader reader;
    private final PrintWriter writer;
    
    public StdioTransport() throws Exception {
        // 建议改为动态获取路径
        File jarFile = new File("target/java-mcp-1.0-SNAPSHOT.jar");
        if (!jarFile.exists()) {
            throw new FileNotFoundException("JAR文件不存在: " + jarFile.getAbsolutePath());
        }

        ProcessBuilder pb = new ProcessBuilder("java", "-jar", jarFile.getAbsolutePath());
        pb.directory(new File(System.getProperty("user.dir"))); // 设置工作目录
        this.process = pb.start();


        // 使用明确的UTF-8编码
        this.reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
        this.writer = new PrintWriter(
                new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));

        //todo 启动一个线程来读取服务端的输出

        // new Thread(() -> {
        //     try {
        //         String line;
        //         while ((line = reader.readLine()) != null) {
        //             System.out.println("服务端输出: " + line);
        //         }
        //     } catch (IOException e) {
        //         e.printStackTrace();
        //     }
        // }).start();
    }
    
    @Override
    public String send(String request) throws Exception {
        // 发送请求
        writer.println(request);
        writer.flush();

        // 读取响应，跳过服务端启动信息
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("{")) {
                return line;
            }
        }
        return null;
    }
    
    @Override
    public void close() throws Exception {
        reader.close();
        writer.close();
        process.destroy();
    }
}